﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using nanoCMS.Core.Concrete;
using nanoCMS.Core.Providers;

namespace nanoCMS.Core {
	public static class SessionManagerBase {

		public static User CurrentUser {
			get {
				if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated == false) return null;
				var data = System.Web.HttpContext.Current.Session["CurrentUser"];
				return data as User;
			}
			set { System.Web.HttpContext.Current.Session["CurrentUser"] = value; }
		}

		public static int CurrentUserID
		{
			get
			{
				if (CurrentUser == null) throw  new Exception("No logged in user");
				return CurrentUser.UserID;
			}
		}

		internal static List<UserInRole> CurrentUserRoles {
			get {
				var data = System.Web.HttpContext.Current.Session["CurrentUserRoles"];
				return data != null ? data as List<UserInRole> : null;
			}
			set { System.Web.HttpContext.Current.Session["CurrentUserRoles"] = value; }
		}

		public static bool IsAdmin
		{
			get {
				if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated == false) return false;
				if (CurrentUser == null) return false;
				if (!System.Web.HttpContext.Current.Items.Contains("TenantID")) return false;

				int tenantId = Convert.ToInt32(System.Web.HttpContext.Current.Items["TenantID"]);

				return CurrentUserRoles.Any(x => x.UserID == CurrentUser.UserID && x.TenantID == tenantId && x.RoleID == 1);
			}
		}
		
		public static bool IsRoot
		{
			get
			{
				if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated == false) return false;
				if (CurrentUser == null) return false;
				var rootUser = Convert.ToInt32(ConfigurationManager.AppSettings.Get("RootUserID"));
				return rootUser == CurrentUser.UserID;
			}
		}

		public static bool IsAuthenticated
		{
			get
			{
				if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated == false) return false;
				if (CurrentUser == null) return false;
				
				return true;
			}
		}

		public static int CurrentLanguage {
			get {
				var data = System.Web.HttpContext.Current.Session["CurrentLanguage"];
				if (data != null) return Convert.ToInt32(data);
				//TODO: Test, no idea if it works
				int defaultLangId = new LanguageProvider(DependencyResolver.Current.GetService<Entities>()).GetDefault().LangID;
				return CurrentLanguage = defaultLangId;
			}
			set { System.Web.HttpContext.Current.Session["CurrentLanguage"] = value; }
		}


	}
}
